import axios from "axios";
import Vue from "vue";
import querystring from "querystring"
import {errorAlert, successAlert} from "../utils/alert"
import store from "../store"
import router from "../router"

//1.环境配置
if (process.env.NODE_ENV === "development") {
    Vue.prototype.$pre = "http://localhost:2000"
}
if (process.env.NODE_ENV === "production") {
    Vue.prototype.$pre = ""
}

//2.请求拦截
axios.interceptors.request.use(config => {
    //每次请求都要执行的逻辑
    if(config.url=="/api/userLogin"){
        config.headers.authorization = store.getters.userInfo.token;
    }
    return config;
})

//3.响应拦截
axios.interceptors.response.use(res => {
    if(res.data.code !==200){
        errorAlert(res.data.msg)
    }
    //掉线处理
    if(res.data.msg=="登录已过期或访问权限受限"){
        //清除vuex和本地储存数据
        store.dispatch("changeUser",{})
        successAlert("登陆已过期")
        //跳转登陆
        router.replace("/login");
    }
    return res;
})

//封装get方法
export const get = (url,params)=>{
    return axios({
        url,
        method:"get",
        params
    })
}

//封装post方法
export const post = (url,params,haveFile = false)=>{
    let data = null;
    if(haveFile){
        data = new FormData()
        for(let i in params){
            data.append(i,params[i])
        }
    }else{
        data = querystring.stringify(params)
    }
    return axios({
        url,
        method:"post",
        data
    })
}